
package com.start.shop.common.exception;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.start.shop.common.constant.MsgObject;
import com.start.shop.common.constant.RspCode;


/**
 * 自定义错误处理器
 * @author Fanruguo
 */

@Controller
@RestControllerAdvice
public class DefaultExceptionHandlerConfig {

	private Logger logger = LoggerFactory.getLogger(DefaultExceptionHandlerConfig.class);

    @ExceptionHandler(BindException.class)
    public ResponseEntity<MsgObject> bindExceptionHandler(BindException e){
    	logger.error("BindException:",e);
        String errMsg = "";
        for (int i = 0; i < e.getBindingResult().getFieldErrors().size(); i++) {
        	logger.error("{}",e.getBindingResult().getFieldErrors().get(i).getDefaultMessage());
			errMsg = errMsg + "【" +e.getBindingResult().getFieldErrors().get(i).getDefaultMessage() + "】";
		}
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(MsgObject.fail(RspCode.PARAM_ERROR.getCode(), errMsg));

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<MsgObject> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
    	logger.error("MethodArgumentNotValidException:",e);
        String errMsg = "";
        for (int i = 0; i < e.getBindingResult().getFieldErrors().size(); i++) {
			errMsg = errMsg + "【" +e.getBindingResult().getFieldErrors().get(i).getDefaultMessage() + "】";
		}
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(MsgObject.fail(RspCode.PARAM_ERROR.getCode(), errMsg));
    }

    @ExceptionHandler(MyException.class)
    public ResponseEntity<MsgObject> unauthorizedExceptionHandler(MyException e){
    	logger.error("ApiShopException:",e);
        return ResponseEntity.status(e.getHttpCode()).body(MsgObject.fail(e.getCode(), e.getMessage()));
    }
    
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<MsgObject> RuntimeExceptionHandler(RuntimeException e){
    	logger.error("RuntimeException:",e);
        return ResponseEntity.status(HttpStatus.OK).body(MsgObject.fail(RspCode.FAIL.getCode(), RspCode.FAIL.getMessage()));
    }
}